<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\SendMail;
use App\Model\HomeUserModel;
use App\Model\HomeUserCaptcha;
use Illuminate\Support\Facades\Redis;
use App\Http\Requests\HomeUserBindEmailValidata;
use App\Http\Controllers\Home\ShowLinksController;
use App\Http\Controllers\Api\IndexApi;


class HomeUserBindEmailController extends Controller
{
    // 显示绑定邮箱页
    public function BindEmail(Request $request)
    {
        // 判断id是否为空
        if (empty($request->id)) {
            return view('notfound');
        }

        // 取出session的值
        $user = $request->session()->get('Homeuser-data');

        if (empty($user)) {
            return redirect()->route('home.login')->with('message', '请先登录!');
        }

        // 判断是否已注册
        if (!empty($user['email'])) {
            return redirect()->back();
        }

        // 查找用户手机
        $userinfo = HomeUserModel::select('id', 'phone')->where('id', $request->id)->first();
        // 判断用户是否合法


        if (empty($userinfo)) {
            return view('notfound');
        }

        if ($user['id'] != $userinfo->id) {
            return view('notfound');
        }

        // 站点信息类
        $type = new IndexApi;
        $index = new ShowLinksController;

        // 获取站点信息
        $sate = IndexApi::getSate();
        $linksArray = $index->index();

        // 返回视图
        return view('Home.goods-bindemail', ['phone' => $userinfo, 'sate' => $sate, 'linksArray' => $linksArray]);
    }

    // 验证绑定表单
    public function DoBindEmail(HomeUserBindEmailValidata $request)
    {
        // 查找用户session
        $user = $request->session()->get('Homeuser-data');

        // 判断是否登录
        if (!$user) {
            return redirect()->route('home.login')->with('message', '请先登录');
        }

        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->phone],
            ['type', '=', 4],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();
        // 判断该用户是否非法
        if(empty($captcha)) {
            return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '服务器繁忙请重试!');
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            $result = HomeUserCaptcha::where([
                ['captchaIndex', '=',$request->phone],
                ['type', '=', 4],
            ])->delete();
            return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '验证码超时，请重新获取!');
        }

        // 判断是否验证成功
        if ($request->emailcode == $captcha->captcha) {

            // 准备键名
            $hashkey = 'home_user_hash_phone:'.$request->phone;

            // 获取用户信息
            $mysqluser = HomeUserModel::select('id', 'username', 'sex', 'pic', 'email', 'member')
                ->where('phone', $request->phone)->get();

            // 判断该用户是否存在
            if (isset($mysqluser[0])) {

                // 判断是否已绑定邮箱
                if (empty($mysqluser[0]->email)) {
                    // 修改数据
                    HomeUserModel::where('phone', $request->phone)
                    ->update([
                      'email' => $request->bindemail,
                    ]);

                    // 准备redis键名
                    $userkey = 'home_user_hash_phone:'.$request->phone;

                    // 查找redis
                    $redisuser = Redis::hGetAll($hashkey);

                    // 判断是否存在
                    if ($redisuser) {
                        // 删除redis用户
                        Redis::del($hashkey);
                        // 重新添加
                        $userinfo = Redis::hMSet($userkey, [
                            'id'         => $redisuser['id'],
                            'username'   => $redisuser['username'],
                            'passname'   => $redisuser['password'],
                            'sex'        => $redisuser['sex'],
                            'pic'        => $redisuser['pic'],
                            'email'      => $request->bindemail,
                            'phone'      => $redisuser['phone'],
                            'user_status'=> $redisuser['user_status'],
                            'member'     => $redisuser['member'],
                            'created_at' => $redisuser['createtime'],
                        ]);
                    }

                    // 退出登录
                    session(['Homeuser-data' => []]);

                    // 准备登陆数据
                    $newuser = [
                        'id'         => $mysqluser[0]->id,
                        'username'   => $mysqluser[0]->username,
                        'sex'        => $mysqluser[0]->sex,
                        'pic'        => $mysqluser[0]->pic,
                        'email'      => $request->bindemail,
                        'member'     => $mysqluser[0]->member,
                    ];

                    // 登录成功
                    session(['Homeuser-data' => $newuser]);

                    // 绑定成功跳转
                    return redirect()->route('home.user');

                    // 删除使用过的验证码
                    $result = HomeUserCaptcha::where([
                        ['captchaIndex', '=',$request->phone],
                        ['type', '=', 4],
                    ])->delete();
                } else {
                    // 用户邮箱已绑定
                    return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '您已绑定邮箱，无需重复绑定');
                }
            } else {
                // 找不到用户
                return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '为找到该用户');
            }
        } else {
            // 验证码错误返回
            return redirect()->route('home.bindemail', ['id' => $user['id']])->with('message', '验证码错误');
        }
    }

    // 发送邮箱验证码
    public function SendEmailCode(Request $request)
    {
      // 查询该用户的验证码
      $captcha = HomeUserCaptcha::where([
          ['captchaIndex', '=', $request->phone],
          ['type', '=', 4],
        ])
        ->orderBy('validperiod', 'desc')
        ->first();

        if ($captcha) {

            // 判断是否手贱
            if ($captcha->validperiod > time()) {
                return 403;
            }
        }

        // 获取用户名
        $user = $request->session()->get('Homeuser-data');

        // 得到对象
        $send = new SendMail;

        $title = '您的邮箱绑定码!';

        // 发送验证码
        $result = $send->send($user['username'], $request->bindemail, $title);

        // 保存记录
        HomeUserCaptcha::insert([
            'captchaIndex'       => $request->phone,
            'captcha'     => $result['code'],
            'validperiod' => $result['end_time'],
            'type'        => $result['type'],
        ]);

        return 123;
    }

    // 判断邮箱是否存在
    public function ValidataEmail(Request $request)
    {

        // 查询数据库是否已注册
        $result = HomeUserModel::where('email', $request->bindemail)->get();

        if (isset($result[0])) {
            // 已注册返回1
            return 1;
        }
        // 未注册返回2
        return 2;

    }

    public function ValidataEmailCode(Request $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->phone],
            ['type', '=', 4],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();
        // 判断是否有该用户的验证码
        if (!$captcha) {
            return 500;
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            return 403;
        }

        // 判断是否验证成功
        if ($request->code == $captcha->captcha) {
            return 200;
        }

        return 500;
    }
}
